package com.xzh.wms.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.xzh.smart.core.exception.BizException;
import cn.xzh.smart.core.util.UserSessionContext;
import com.xzh.wms.dao.PoItemDao;
import com.xzh.wms.dao.PoMasterDao;
import com.xzh.wms.entity.PoItem;
import com.xzh.wms.entity.PoMaster;
import com.xzh.wms.entity.PoMasterQuery;
import com.xzh.wms.enums.PoStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
 /**
 * 采购单头;(206_po_master)表服务实现类
 * @author : heimi
 * @date : 2024-11-25
 */
@Service
@Slf4j
public class PoMasterService {
     
    @Autowired
    private PoMasterDao poMasterDao;

     @Autowired
     private PoItemDao poItemDao;


    public List<PoMaster> select(PoMasterQuery query) {
        return poMasterDao.select(query);
    }


    public Integer insert(PoMaster poMaster) {
        String poId="Po"+ DateUtil.format(DateUtil.date(),"yyyyMMddHHmmssSSS");
        poMaster.setId(poId);
        List<PoItem> items = poMaster.getPoItems();
         BigDecimal totalPrice = BigDecimal.ZERO;
        for (PoItem item : items){
            item.setPoId(poId);
            item.setLastUpdateBy(UserSessionContext.get().getNickName());
            totalPrice= NumberUtil.add(totalPrice,NumberUtil.mul(item.getPrice(),item.getQty()));
            //单独添加
            //poItemDao.insert(item);
        }
        //检验总价
        if(totalPrice.doubleValue() !=poMaster.getTotalPrice()){
            throw new BizException(453,"价格计算有误");
        }
        //判断是否超过制定价格
         if(poMaster.getTotalPrice()>5000){
             sentDingDing(poId,totalPrice);
         }else {
             poMaster.setStatus(PoStatus.APPROVE.getCode());
         }
        //批量添加
        PoMasterService poMasterService  = (PoMasterService) AopContext.currentProxy();
        poMasterService.save(poMaster);
        return 0;
    }

     @Transactional()
    public void save(PoMaster poMaster){
        poMasterDao.insert(poMaster);
        poItemDao.insertBatch(poMaster.getPoItems());

    }

     private static final String DingDingUrl="https://oapi.dingtalk.com/robot/send?access_token=a11501e83032b7b7ddc82fe36bca6bfc8815d85a75982b2943c195b7fdc9f102";

     private void sentDingDing(String poId,BigDecimal totalPrice){
         JSONObject json1= JSONUtil.createObj();
         json1.putOpt("msgtype","text");
         String format = StrUtil.format("警告：{}的采购单{}，金额为：{}，需要您的审批。", UserSessionContext.get().getNickName(), poId,totalPrice);
         json1.putOpt("text",JSONUtil.createObj().putOpt("content",format));
         json1.putOpt("isAtAll",false);
         JSONArray array = JSONUtil.createArray();
         array.add("1879051053");
         json1.putOpt("atMobiles",array);

         String json = JSONUtil.toJsonStr(json1);
         String result2 = HttpRequest.post(DingDingUrl)
                 .body(json)
                 .execute().body();

         JSONObject jsonObject = JSONUtil.parseObj(result2);
         Object errcode = jsonObject.get("errcode");
         if(errcode.equals(0)){
             log.debug("发送钉钉成功");
         }else{
             log.error("发送钉钉失败：{}",jsonObject.get("errmsg"));
         }
     }

    public Integer update(PoMaster poMaster) {
        return poMasterDao.update(poMaster);
    }
    
    public Integer delete(Integer id) {
        return poMasterDao.delete(id);
    }

 }